//    Copyright (C) Kherty.  All rights reserved.
using System;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet
{
    public class CustomFilters : Filter
    {
        internal override void ReadXmlCore(ReadContext context)
        {
            using (ReadContext c = context.Read("customFilters"))
            {
                And = c.GetOptionalBoolean("and", false);
                First = c.ReadElement<CustomFilter>();
                Second = c.ReadOptionalElement<CustomFilter>("customFilter");
            }
        }

        internal override void WriteXmlCore(WriteContext context)
        {
            using (WriteContext c = context.Write("customFilters"))
            {
                c.SetOptionalBoolean("and", And, false);
                c.WriteElement(First);
                c.WriteOptionalElement(Second);
            }
        }
        private CustomFilter first = new CustomFilter();

        public CustomFilter  First
        {
            get { return first; }
            set { first = value; }
        }

        public CustomFilter Second { get; set; }


        public bool And { get; set; }


        internal override bool GetValue(Cell cell, RangeAddress rangeAddress)
        {
            bool b1 = First.GetValue(cell);
            if (Second == null)
                return b1;
                bool b2 = Second.GetValue(cell);
                if (And)
                    return b1 && b2;
                return b1 || b2;
            }

        internal override Func<Cell, bool> GetCellEvaluator(Range range)
        {
            return cell =>
                       {
                           bool b1 = First.GetValue(cell);
                           if (Second == null)
                               return b1;
                           bool b2 = Second.GetValue(cell);
                           if (And)
                               return b1 && b2;
                           return b1 || b2;
                       };
        }
    }
        
    
}
